import java.util.LinkedList;
import java.util.List;

/**
 * 
 * 
 * @param n 括号组合长度，闭区间1到8
 */
class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> res = new LinkedList<>();
        char[] path = new char[2*n];

        int left = 0, right = 0;
        backTrace(n, 0, left, right, path, res);
        return res;

    }

    private void backTrace(int n, int depth, int left, int right , char[] path, List<String> res){
        if (depth == 2*n){
            res.add(new String(path));
            return;
        }

        if (left < n) {
            path[depth] = '(';
            backTrace(n, depth+1, left+1, right, path, res);
        }
        if (right < left) {
            path[depth] = ')';
            backTrace(n, depth+1, left, right+1, path, res);
        }
    }
}